# -*- coding:utf8 -*-
#encoding = utf-8

from flask import Flask
from flask import Flask,request,g,render_template,redirect,url_for,abort,session
from flask import make_response,Response,send_from_directory
import redis
from redis import StrictRedis
from flask_session import Session
import sys,os
import json
import time
from datetime import datetime,timedelta
from io import StringIO, BytesIO

import api.open_redis as open_redis


import random

app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('FLASKR_SETTINGS',silent=True)

app.config['SECRET_KEY']=os.urandom(24)   #设置为24位的字符,每次运行服务器都是不同的，所以服务器启动一次上次的session就清除。
app.config['PERMANENT_SESSION_LIFETIME']=60*60*24 #session长期有效，则设定session生命周期，整数秒，默认大概不到3小时。

app.config['SESSION_TYPE'] = 'redis'  # session类型为redis
app.config['SESSION_KEY_PREFIX'] = 'session:'  # 保存到session中的值的前缀
app.config['SESSION_REDIS'] = StrictRedis(host='127.0.0.1', port='6379')#, password='')  # 用于连接redis的配置

#上传文件最大 2MB
app.config['MAX_CONTENT_LENGTH'] = 20*1024*1024



#声明 蓝图

#登陆模块
from api.wenzhang import wenzhang
app.register_blueprint(wenzhang)
import api.wenzhang as wz_function


#查询模块
from api.login import login
app.register_blueprint(login)
import api.login as login_function

'''
#收藏模块
from api.collect import collect
app.register_blueprint(collect)
import api.collect as collect_function


#用户模块
from api.user import user
app.register_blueprint(user)
import api.user as user_function



#PC端显示模块
from api.pc_home import pchome
app.register_blueprint(pchome)
import api.pc_home as pchome_function



#使用公用方法
import api.public as pub
'''

Session(app)

def Response_headers(content):  
    resp = Response(content)  
    resp.headers['Access-Control-Allow-Origin'] = '*'  
    return resp  










#我的
@app.route('/my', methods=['POST','GET'])
def my_pg():
    return render_template('my.html',my=1)


#文章内容
@app.route('/ysinfo', methods=['POST','GET'])
def ysinfo_pg():
    return render_template('ysinfo.html')


#查询界面  /cxpg
@app.route('/cxpg', methods=['POST','GET'])
def fenlei_pg():
    return render_template('fenlei.html')



#获取IP
def get_user_ip():
    print(request.remote_addr)
    return request.remote_addr


#用户身份识别
def userACC():
    userToken=request.cookies.get('user_token')
    print("[Get Cookies] = "+str(userToken))
    username=request.cookies.get('user_name')
    print("[Get username] = "+str(username))

    keys = session.get(userToken)
    print("[Get keys] = "+str(keys))
    if userToken != None and keys == username:
        return True
    else:
        return False






'''
@app.route('/downloadpg',methods=['POST','GET'])
def download_pg():
    return render_template('downapp.html',home=1)



@app.route('/downloadapp',methods=['POST','GET'])
def download_app():

    Man_API_Path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    print(Man_API_Path)
    filepath = Man_API_Path+"/hbsj_v0.14/"
    filename = "hbsjAPP-v0.1.5.apk"
    #普通下载
    response = make_response(send_from_directory(filepath, filename, as_attachment=True))
    response.headers["Content-Disposition"] = "attachment; filename={}".format(filepath.encode().decode('latin-1'))
    return send_from_directory(filepath, filename, as_attachment=True)
    #return "0"
    '''



@app.errorhandler(403)
def page_not_found(error):
    content = json.dumps({"error_code": "403"})
    resp = Response_headers(content)
    return resp

@app.errorhandler(404)
def page_not_found(error):
    content = json.dumps({"error_code": "404"})
    resp = Response_headers(content)
    return resp

@app.errorhandler(400)
def page_not_found(error):
    content = json.dumps({"error_code": "400"})
    # resp = Response(content)
    # resp.headers['Access-Control-Allow-Origin'] = '*'
    resp = Response_headers(content)
    return resp
    # return "error_code:400"

@app.errorhandler(410)
def page_not_found(error):
    content = json.dumps({"error_code": "410"})
    resp = Response_headers(content)
    return resp

@app.errorhandler(500)
def page_not_found(error):
    content = json.dumps({"error_code": "500"})
    resp = Response_headers(content)
    return resp

    



if __name__ == '__main__':
    #启动redis
    #open_redis.start_redis()
    app.run(host="0.0.0.0",port=9393,debug=True,threaded=True)